package cn.easyutil.project.web.handler;

import cn.easyutil.project.base.bean.ResponseBody;
import cn.easyutil.project.base.exception.CommonException;
import cn.easyutil.project.base.exception.Error;
import cn.easyutil.project.web.advice.GlobalExceptionAdvice;
import cn.easyutil.project.web.util.RequestPool;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;

public class DefaultGlobalExceptionAdvice implements GlobalExceptionAdvice {
    @Override
    public Object parseResponseBody(Exception e) {
        ResponseBody result = new ResponseBody();
        result.setCode(RequestPool.ERRORCODE);
        result.setErrCode(-1);
        result.setErrMsg(e.getMessage());
        result.setErrMsgDesc(e.getMessage());

        // 处理dto验证异常
        if (e instanceof BindException) {
            BindException ex = (BindException) e;
            FieldError fieldError = ex.getBindingResult().getFieldError();

            result.setErrCode(Error.request_params_error.getCode());
            result.setErrMsg(fieldError.getField() + "：" + fieldError.getDefaultMessage());
        }
        // 处理dto验证异常
        else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            FieldError fieldError = ex.getBindingResult().getFieldError();

            result.setErrCode(Error.request_params_error.getCode());
            result.setErrMsg(fieldError.getField() + "：" + fieldError.getDefaultMessage());
        }
        // 处理自定义异常
        else if (e instanceof CommonException) {
            CommonException ex = (CommonException) e;
            result.setErrCode(ex.getErrorCode().getCode());
            result.setErrMsg(ex.getMessage());
            result.setErrMsgDesc(ex.getViewMessage());
        }
        else {
            result.setErrCode(Error.system_error.getCode());
            result.setErrMsg(Error.system_error.getRemark());
        }
        return result;
    }
}
